<template>
  <div>
    <a-card :bordered="false" :bodyStyle="{padding:'16px', height: '100%'}">
      <div style="margin-bottom:20px">
        <a-button type="primary" style="margin-right:10px" @click="$router.push({ name: 'add_record' })">新建成绩表</a-button>
        <!-- <a-button style="margin-right:10px" @click="visible1 = true">导入成绩表</a-button> -->
        <a-button style="margin-right:10px" @click="$refs.subj_model.showModal()">考试科目设置</a-button>
      </div>

      <s-table
        :columns="columnsreportList"
        :data="loadData"
        :rowKey="(record) => record.id"
        class="user_management_table"
        ref="table"
        :pagination="pagination"
      >
        <span slot="name" slot-scope="text, record">
          <a @click="$router.push({ name: 'detail_report', query: { id: record.id } })">{{record.name}}</a>
          <a-tag style="margin-left:8px;" v-if="record.type==2">草稿</a-tag>
        </span>
        <span slot="read_num" slot-scope="text, record">
          <a @click="readyRead(record)">{{record.read_num}}</a>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="$router.push({ name: 'edit_record', query: { id: record.id } })">编辑</a>
          <a-divider type="vertical" />
          <a @click="delreport(record.id)">删除</a>
        </span>
      </s-table>
      <!-- <create-form ref="createModal" @ok="handleOk" /> -->
      <a-modal
        title="导入成绩表"
        :visible="visible1"
        :confirmLoading="updateLoading"
        @ok="handleOk1"
        okText="导入"
        @cancel="visible1=false"
      >
        <div class="updateInfo">
          <div class="line">
            <div class="title">1.下载导入模板，按要求填写信息</div>
            <div style="border: 1px dashed #e8e8e8;padding: 8px;margin:15px 0">
              <p>温馨提示：</p>
              <p>•请不要修改模板格式</p>
            </div>
            <div>
              <a @click="downloadGrade">下载学员信息导入模板</a>
            </div>
          </div>

          <div class="line">
            <div class="title">2.选择需要导入的Excel文件</div>
            <div>
              <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
                <a-button type="primary" :disabled="fileList.length>0">添加文件</a-button>
              </a-upload>
            </div>
          </div>
          <div class="line">
            <div class="title">3.添加备注</div>
            <div>
              <a-input placeholder="最多20字" style="width:300px;" v-model="excelInRemarks" :max-length="20" />
              <p style="font-size:10px;color:#ccc;padding:0 2px;">为导入的文件添加备注，便于在导入记录中查找</p>
            </div>
          </div>
        </div>
      </a-modal>
      <a-modal :title="'考试名称:'+title_name" v-model="visible"  :footer="null" >
        <!-- :bodyStyle="{maxHeight:'400px','overflow-y':'auto'}" -->
        <!-- <a-input-search placeholder="input search text" style="width: 200px" @search="onSearch" /> -->
        <a-table
          :columns="columns"
          :dataSource="readData"
          :pagination="false"
          :rowKey="(record) => record.id"
          class="user_management_table"
          style="border: 1px solid #e8e8e8;"
          :scroll="{  y: 300 }"

        ></a-table>
      </a-modal>
    </a-card>
    <div>
      <router-view></router-view>
    </div>
    <subject-model ref="subj_model" />
  </div>
</template>

<script>
import moment from 'moment'
import topNavBar from '@/components/topNavBar/topNavBar'
import { STable, Ellipsis } from '@/components'
import subjectModel from '@/components/subjectsModel'
import {
  examsList,
  examsdelete,
  subjectsList,
  subjectsCreate,
  subjectsDelete,
  subjectsUpdate,
  examsStudentList
} from '@/api/homeSchool'
import { reportList, downloadExport, excelIn } from '@/api/report'
export default {
  name: 'TableList',
  components: {
    STable,
    subjectModel,
  },
  data() {
    return {
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },
      // title:'',
      visible: false,
      visible1: false,
      modalTableData: [], //科目数据
      readData: [],
      isAddSet: false,
      inputval: '', //输入的值
      newedit: true, //编辑
      editId: '',
      // 高级搜索 展开/关闭
      advanced: false,
      school_id: '',
      title_name: '',
      // 查询参数
      queryParam: {
        school_id: this.$store.state.user.school
      },
      Isteacher: [],
      columns: [
        {
          title: '学员姓名',
          dataIndex: 'student_name',
          align: 'center'
        },
        {
          title: '电话',
          dataIndex: 'phone',
          align: 'center'
        },
        {
          title: '阅读状态',
          dataIndex: 'is_read',
          align: 'center',
          customRender(is_read) {
            return is_read == 1 ? '已读' : '未读' //1已读，2未读
          }
        }
      ],
      columnsreportList: [
        {
          title: '考试名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        // {
        //   title: '',
        //   // dataIndex: 'attend_class_day',
        //   // align: 'center',
        //   customRender: (text, record) => {
        //     const time = `${record.attend_class_day} ${record.start_time}-${record.end_time}`
        //     return time
        //   }
        // },
        {
          title: '考试科目',
          dataIndex: 'subject_name'
        },
        {
          title: '考试时间',
          dataIndex: 'time'
        },
        {
          title: '最高分',
          dataIndex: 'highest_score'
        },
        {
          title: '平均分',
          dataIndex: 'average_score'
        },
        {
          title: '参加考试人数',
          align: 'right',
          dataIndex: 'join_exam_num'
        },
        {
          title: '缺考人数',
          align: 'right',
          dataIndex: 'miss_exam_num'
        },
        {
          title: '是否展示给家长',
          dataIndex: 'is_show',
          customRender(is_show) {
            return is_show == 1 ? '展示' : '不展示' //1展示，2不展示
          }
        },
        {
          title: '已读/全部',
          dataIndex: 'read_num',

          scopedSlots: { customRender: 'read_num' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return reportList(Object.assign(parameter, this.queryParam)).then(res => {
          return res
        })
      },
      //导入
      fileList: [],
      excelInRemarks: '',
      updateLoading: false,
      //考试科目
      dataScore: [],
      addDataScoreType: false,
      columnsScore: [
        {
          title: '科目',
          scopedSlots: { customRender: 'subject' }
        },
        {
          title: '操作',
          align: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },

  created() {

    this.getsubjectsList()
  },

  mounted() {

    this.school_id = this.$store.state.user.school //获取school_id
  },
  methods: {
    //设置科目
    // 获取科目列表
    getsubjectsList() {
      subjectsList({ pageSize: 999999999, school_id: this.$store.state.user.school })
        .then(res => {
          this.dataScore = res.data
          this.dataScore.forEach(item => {
            item.flag = false
          })
        })
        .catch(err => {
          this.$message.error(err.data.message || '科目列表获取失败')
        })
    },
    readyRead(e) {
      this.title_name = e.name
      examsStudentList(e.id).then(res => {
        this.readData = res.data
        this.visible = true
      })
    },
    onClose() {
      this.isAddSet = false
      this.inputval = '' //输入的值
      this.editId = ''
    },
    //操作删除
    delreport(id) {
      let that = this
      that.$confirm({
        title: '删除成绩表',
        content: '删除后，家长无法查看本次成绩，且数据无法恢复',
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          examsdelete(id)
            .then(res => {
              that.$message.success('成绩单删除成功')
              that.$refs.table.refresh()
            })
            .catch(err => {
              that.$message.error(err.data.message || '成绩单删除失败')
            })
        },
        onCancel() {
        }
      })
    },
    addSet() {
      if (!this.isAddSet && this.newedit) {
        this.isAddSet = true
      }
    },
    messagedel(id) {
      //删除已有的设置
      let _this = this
      this.$confirm({
        title: '删除该设置会影响别的数据，是否继续?',
        icon: 'warning',
        onOk() {
          subjectsDelete({ subject_ids: [id] })
            .then(res => {
              subjectsList({ pageSize: 99999 }).then(res => {
                _this.isAddSet = false
                _this.inputval = ''
                _this.modalTableData = res.data
              })
            })
            .catch(res => {
              console.log(err)
            })
        },
        onCancel() {
        }
      })
    },
    messagesave() {
      //保存新的设置
      if (this.inputval !== '') {
        subjectsCreate({ school_id: this.school_id, name: this.inputval })
          .then(res => {
            subjectsList({ pageSize: 99999 })
              .then(res => {
                this.isAddSet = false
                this.inputval = ''
                this.modalTableData = res.data
              })
              .catch(err => {
                this.$message.error(err.data.message || '获取失败')
              })
          })
          .catch(err => {
            this.$message.error(err.data.message || '保存失败')
          })
      } else {
        this.$message.error('请输入科目')
      }
    },
    messagenosave() {
      //保存不的设置
      this.isAddSet = false
      this.inputval = ''
    },
    messagedEdit(data) {
      this.editId = data.id
      this.newedit = false
      if (this.isAddSet) {
        this.inputval = ''
        this.isAddSet = false
      }
    },
    messagednewsave(data) {
      let _this = this
      subjectsUpdate({ name: data.name }, data.id).then(res => {
        subjectsList({ pageSize: 99999 }).then(res => {
          _this.isAddSet = false
          _this.inputval = ''
          _this.modalTableData = res.data
          this.editId = ''
          this.newedit = true
        })
      })
    },
    //导入
    handleOk1() {
      if (this.fileList.length < 1) {
        this.$message.error('请选择上传文件')
      }
      this.updateLoading = true
      let that = this
      const formData = new FormData()
      formData.append('excel', that.fileList[0])
      formData.append('school_id', this.$store.state.user.school)
      formData.append('remark', this.excelInRemarks)
      excelIn(formData)
        .then(res => {
          this.updateLoading = false
          this.updateModal = false
          this.$refs.table.refresh()
          this.$message.success('导入成功')
        })
        .catch(err => {
          this.updateLoading = false
          this.$message.error(err.data.message || '导入失败')
        })
    },
  
    downloadGradeTemplate(blobUrl, name) {
       const a = document.createElement('a')
      a.style.display = 'none'
      a.download = name
      a.href = blobUrl
      a.click()
      document.body.removeChild(a)
    },

    downloadGrade() {
      downloadExport(this.$store.state.user.school).then(res => {
        let blobUrl = window.URL.createObjectURL(res)
        this.downloadGradeTemplate(blobUrl,'学员信息导入模板')
      })
    },
    beforeUpload(file) {
      this.fileList = [file]
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        this.fileList = []
        return false
      }
      if (!isLt5M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        this.fileList = []
        return false
      }
      return false
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
  }
}
</script>
<style lang="less" scoped>
.expand_warning {
  margin: 16px 0;
  background-color: #fff0e7;
  border-radius: 4px;
}
.updateInfo {
  .line {
    margin-bottom: 16px;
    .title {
      margin-bottom: 3px;
    }
  }
}
// .antput {
//   border: none;
//   outline: none;
//   // border-bottom: 1px solid #ffab1a !important;
//   width: 260px;
//   border-radius: 0;
// }
// .user_management_table{
// margin-right:20px
// }
</style>